#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define MAXLINE 80
#define SERV_PORT 8000

int main(void)
{
    struct sockaddr_in serv_addr, cli_addr;
    socklen_t cli_addr_len;
    int listen_fd, conn_fd;
    char buf[MAXLINE];
    char str[INET_ADDRSTRLEN];
    int i, n;

    listen_fd = socket(AF_INET, SOCK_STREAM, 0);

    bzero(&serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(SERV_PORT);

    bind(listen_fd, (struct sockaddr *)&serv_addr, \
            sizeof(serv_addr));
    listen(listen_fd, 20);

    printf("Accepting connections ...\n");
    while (1) {
        cli_addr_len = sizeof(cli_addr);
        conn_fd = accept(listen_fd, (struct sockaddr *)&cli_addr, \
                &cli_addr_len);
        n = read(conn_fd, buf, MAXLINE);
        printf("received from %s at PORT:%d\n", \
                (char *)inet_ntop(AF_INET, &cli_addr.sin_addr, \
                    str, sizeof(str)), \
                ntohs(cli_addr.sin_port));
        for (i = 0; i < n; i++)
            buf[i] = toupper(buf[i]);
        write(conn_fd, buf, n);
        close(conn_fd);
    }
}

